<?php
namespace control;

/*
*食堂采购记录类
*/

class canteenClass extends adIndexClass
{
    private const page = 'canteen';
    private const table = 'canteen';
    private const tableMx = 'canteen_detail';
    private const title = '食堂采购记录';
    public array $stateOption = ['草稿', '待复核', '已复核'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'purchaseDate'          => [
                        'name'  => '日期',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "单号",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => "食堂名称",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'total'         => [
                        'name'  => "金额(". static::$unit . ")",
                        'width' => 200,
                    ],
                    'stid'          => [
                        'name'  => '制单人',
                        'width' => 200,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单号"     => text(array("name" => "orderNo")),
                    "食堂名称"     => select(array("name" => "name", 'option' => explode('，', para('canteenOption')))),
                    "制单人" => selectMultiple(array("name" => "stid", "class" => "width200", "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid')),
                ],
                [
                    "日期"     => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态"     => select(array("name" => "state", "option" => $this->stateOption)),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "stid" => $this->post('stid'),//申请人
            "name" => $this->post('name'),//食堂名称
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'purchaseDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'purchaseDate desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "total":
                        $result = find(array('table' => self::tableMx, 'single' => " orderId = '$array[id]'", 'field' => "ifnull(sum(price*num),0) as total"));
                        $row[] = round($result['total'], 2);
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find(array('table' => self::tableMx, 'single' => " orderId in (select id from ".self::table." where 1=1 {$where}) ", 'field' => "ifnull(sum(price*num),0) as total"));
        $total    = [
            'total'        => self::lostZero($totalQuery['total']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id =  $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" .$id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    "日期：" => text(["name" => "purchaseDate", 'class' => 'select', 'laydate' => [], "value" => $info['purchaseDate']]),
                    must . "食堂名称：" => selectMultiple(array("name" => "hallId", 'value' => $info['hallId'], "title" => "食堂名称", 'table' => "dining_hall", 'where' => "state = '启用'", 'sqlId' => 'id', 'sqlField' => 'name'))
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']])
                        . hidden(['name' => 'id', 'value' => $info['id'] ?:$id]),
                ],
            ],
        ]);
        //返回
        return $this->layer(array(
            "title" => L('job.button.editor').self::title,
            "height" => 250,
            "html" => $html,
            'button' => '<button class="button" onclick="subForm(\'' . self::page . 'EditForm\',root+\'control/adIndex.html?cla=' . self::page . '&fun=editEdit\')">下一步</button>'
        ));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'purchaseDate' => $this->post('purchaseDate'),
            'hallId' => $this->post('hallId'),
            'text' => $this->post('text'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'purchaseDate' => '日期',
            'hallId' => '食堂名称',
        ];
        $rules = [
            'purchaseDate' => 'required',
            'hallId' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } else {
            $hall = query('dining_hall', "id = '$field[hallId]'");
            $field['name'] = $hall['name'];
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'FP' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['iframe'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                $json['iframeName'] = self::title;
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            $_SESSION[self::page]['id'] = $info['id'];
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );
            $button = [];
            $mxButton = '';//目标按钮
            if ($this->power(self::page, "edit")) {
                if ($info['state'] == '草稿') {
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "edit",
                        "post" => ["id" => $info['id']],
                    ];
                    $mxButton = "
                        <span class='smallButton' onclick=\"layer('" . self::page . "','addMx',{id:'" . suiji() . "',mainId:'" . $info['id'] . "'})\">新增</span>
                        <span class='smallButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',act:'delMx'})\">删除</span>
                        <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=downloadModel'><span class='smallButton'>导入模板</span></a>" .
                        $this->upButton(array("title" => "导入", "fun" => "medicalInsuranceUpload", "buttonClass" => "smallButton")) . "
                        <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='smallButton'>导出</span></a>\n
                    ";
                }
            }
            if ($this->power(self::page, 'del') && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }

            if ($this->power(self::page, "confirm") && $info['state'] == '待复核') {
                $button[] = [
                    "name" => "确认",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }

            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
            $checkAll = $this->checkAll("detailForm", "mxId");
            $tr[] = [$checkAll, '供应商', '类别', '品名', '数量', '单价(' . static::$unit . ')', '金额(' . static::$unit . ')', '备注'];
            foreach ($result['array'] as $val) {
                //列表控件
                $dominate = array(
                    "box" => array("name" => "mxId", "value" => $val['id']),
                    "edit" => $info['state'] =='已复核'?[]:array("title" => "编辑", "click" => "layer('" . self::page . "','addMx',{id:'" . $val['id'] . "',mainId:'" . $info['id'] . "'})"),
                );

                $tr[] = [$this->dominate($dominate), $val['supplierName'], $val['type'], $val['materialName'], $val['num'], $val['price'], round($val['num'] * $val['price'], 2), $val['text']];
            }
            $total = find(array(
                'table'  => self::tableMx,
                'field'  => "ifnull(sum(num),0) as num,ifnull(sum(round(num*price,2)),0) as totalMoney",
                'single' => "orderId = '$info[id]' order by list asc"
            ));
            $total_tr = [
                4=>self::lostZero($total['num'], 'numPrecision'),
                6=>self::lostZero($total['totalMoney']),
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        "单号" => $info['orderNo'],
                        "日期" => $info['purchaseDate'],
                        "食堂名称" => $info['name'],
                        "制单人" => self::findStaff($info['stid']),
                    ),
                    array(
                        "制单时间" => $info['time'],
                        "复核时间" => self::null($info['checkTime']),
                        "状态" => $info['state'],
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '新增明细',
                'button' => $mxButton,
                'html' => "<div class='purchaseMx'>
                                <form name='detailForm'>" . hidden(array('name' => 'id', 'value' => $info['id'])) . $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total_tr, 'showSort' => true)) . "</form>
                            </div>",
            ]);
            //生成页面
            $html = $this->tab($data) . $this->js();
        }
        //返回
        return $html;
    }

    public function js(): string
    {
        return <<<eof
<script>
function setSupplierName(e){
    let val = e.value;
    $(e).next().val(val);
}
</script>
eof;

    }


    /**
     * 下载模板
     */
    public function downloadModel()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $title = ['供应商', '类别', '品名', '数量', '单价(' . static::$unit . ')', '金额(' . static::$unit . ')', '备注'];
            $data[] = [];
            $text = $this->control['name'] . "下载了食堂采购记录明细导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, '食堂采购记录明细导入模板.xlsx');
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/
    public function medicalInsuranceUpload()
    {
        $id = $_SESSION[self::page]['id'];
        $info = query(self::table, " id = '$id'");
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } elseif (!$info['id']) {
            $_SESSION['warn'] = '未找到此食堂采购记录';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            foreach ($data as $i => $row) {
                if ($i > 0) {
                    $cell = formSubArray($row);
                    $field = [
                        "id" => self::getId(),
                        "time" => $this->time,
                        'orderId' => $info['id'],
                        'updateTime' => $this->time,
                        'supplierName' => $cell[0],
                        'type' => $cell[1],
                        'materialName' => $cell[2],
                        'num' => $cell[3],
                        'price' => $cell[5],
                        'text' => $cell[6],
                    ];
                    $annotation = [
                        'supplierName' => '供应商名称',
                        'type' => '类型',
                        'materialName' => '品名',
                        'num' => '数量',
                        'price' => '单价',
                    ];
                    $rules = [
                        'supplierName' => 'required',
                        'type' => 'required',
                        'materialName' => 'required',
                        'num' => 'required',
                        'price' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= "第【{$i}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } else {
                        $warn = insert(["table" => self::tableMx, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$i}】行：导入成功<br>";
                        } else {
                            $text .= "第【{$i}】行：导入失败：编辑失败<br>";
                        }
                    }
                }
            }
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $warn = "成功导入" . $x . "条数据，详情请查看日志！";
            $_SESSION['warn'] = $warn;
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $data = [];
            $id = $_SESSION[self::page]['id'];
            $info = query(self::table, " id = '$id'");
            $title = ['供应商', '类别', '品名', '数量', '单价(' . static::$unit . ')', '金额(' . static::$unit . ')', '备注'];
            $result = find(array('table' => self::tableMx, 'where' => " orderId = '$id' order by list asc"));
            if (is_array($result['array'])) {
                foreach ($result['array'] as $array) {
                    $data[] = [$array['supplierName'], $array['type'], $array['materialName'], $array['num'], $array['price'], round($array['num'] * $array['price'], 2), $array['text']];
                }
            }
            $text = $this->control['name'] . "导出了食堂【{$info['name']}】【{$info['purchaseDate']}】的采购记录明细";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "食堂【{$info['name']}】【{$info['purchaseDate']}】采购记录明细.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }


    /**
     * 添加明细
     * @return bool|string
     */
    public function addMx()
    {
        $mx = query(self::tableMx, " id = '{$this->post('id')}'");
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "供应商：" => repeatSelect(array('name' => 'supplier', 'value' => $mx['supplierName'], 'change' => 'setSupplierName', 'title' => '供应商', 'sqlField' => "supplierName", 'sqlForm' => self::tableMx)) . text(array("name" => "supplierName", "value" => $mx['supplierName'])),
            ),
            array(
                must . "类别：" => select(array("name" => "type", 'title' => '类别', 'option' => explode('，', para('canteenMaterialOption')), "value" => $mx['type'])),
                must . "品名：" => text(array("name" => "materialName", "value" => $mx['materialName'])),
            ),
            array(
                must . "数量：" => text(array("name" => "num", "value" => $mx['num'])),
                must . "单价：" => text(array("name" => "price", 'unit' =>  static::$unit , "value" => $mx['price'])),
            ),
            array(
                "备注：" => textarea(array("name" => "text", "value" => $mx['text'])),
            ),
        ), 'hidden' => hidden(array('name' => 'mainId', 'value' => $this->post('mainId')))
        ));
        //返回
        return $this->layer(array("title" => "新增食材明细", "height" => 360, "width" => 800, "html" => $html));
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '{$this->post('mainId')}'");
        $mx = query(self::tableMx, " id = '$id'");

        $field = [
            'supplierName' => $this->post('supplierName'),
            'type' => $this->post('type'),
            'materialName' => $this->post('materialName'),
            'num' => $this->post('num'),
            'price' => $this->post('price'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'supplierName' => '供应商名称',
            'type' => '类型',
            'materialName' => '品名',
            'num' => '数量',
            'price' => '单价',
        ];
        $rules = [
            'supplierName' => 'required',
            'type' => 'required',
            'materialName' => 'required',
            'num' => 'required',
            'price' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购记录';
        } elseif ($info['state'] == '已复核') {
            $json['warn'] = '此采购记录已复核，不能编辑';
        } else {
            if (empty($mx['id'])) {
                $field = array_merge($field, [
                    'id' => $id,
                    'orderId' => $info['id'],
                    'time' => $this->time,
                ]);
                $json['warn'] = insert(array(
                    "table" => self::tableMx,
                    "field" => $field,
                ));
            } else {
                $json['warn'] = update(array(
                    "table" => self::tableMx,
                    "field" => $field,
                    "where" => "id = '$mx[id]'",
                ));
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "的采购明细，id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此记录？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此记录？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'delMx':
                $act = 'del';
                $msg = '删除采购明细';
                $title = self::table . 'DeleteMx';
                $function = 'deleteMx';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已复核',
            'checkTime' => $this->time
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购记录';
        } elseif ($info['state'] != '待复核') {
            $json['warn'] = '此采购记录不是待复核状态，不能确认';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待复核',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购记录';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此采购记录不是草稿状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除明细
     * @return bool|string
     */
    public function deleteMx()
    {
        $array = $this->post('mxId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $mx = query(self::tableMx, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::tableMx, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
                $text .= "【{$mx['materialName']}】,ID【" . $mx['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了食堂采购明细，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个食堂采购明细，详情见系统日志。";
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }
}

